/**
 * @description 扩展subscription
 */
import pathToRegexp from 'path-to-regexp';

/**
 * @description 获取动态路由中的参数
 * @param {*} url
 * @param {*} pathname
 * @example
 * url: '/repay/12/detail' pathname: '/repay/:id/detail'
 * res: { id: 12 }
 */
const getRouteUrlParams = (url, pathname) => {
  const paramsRes = {};
  const match = pathToRegexp(url).exec(pathname);
  if (match) {
    const params = url.match(pathToRegexp(url)).slice(1);
    const ms = match.slice(1);
    params.forEach((param, index) => {
      if (param) {
        const key = param.slice(1);
        key !== '' && (paramsRes[key] = ms[index]);
      }
    });
  }

  return paramsRes;
};

const listenFunc = ({ listen }) => (pathname, callback) =>
  listen(location => {
    const { pathname: urlPath } = location;
    if (pathname === urlPath || pathToRegexp(pathname).test(urlPath)) {
      const params = getRouteUrlParams(pathname, urlPath);
      /**
       * 执行回调
       */
      callback && callback({ params, ...location });
    }
  });

const createSubscription = (subscriptions, key) => ({ dispatch, history }) =>
  subscriptions[key]({
    dispatch,
    history,
    listen: listenFunc(history),
  });

const createSubscriptions = subscriptions =>
  Object.keys(subscriptions).reduce((next, key) => {
    next[key] = createSubscription(subscriptions, key);
    return next;
  }, {});

export default createSubscriptions;
